package com.ghck.message.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.ghck.message.config.ConfigProperties;
import com.ghck.message.event.JpushEvent;
import com.ghck.message.event.JpushMessageEvent;
import com.ghck.message.event.JpushNotificationEvent;
import com.ghck.message.model.JPushMessage;
import com.ghck.message.model.JPushNotification;
import com.ghck.message.service.JpushService;
import com.ghck.message.util.SpringContextUtil;

import cn.jpush.api.utils.StringUtils;

@Service
public class JpushServiceImpl implements JpushService {
	
	Logger logger=LoggerFactory.getLogger(JpushServiceImpl.class);

	@Autowired
	@Qualifier("config")
	ConfigProperties config;
	
	public String test() {
		System.out.println(config.getTest());
		
		return "just test in boot";
	}
	

	@Override
	public void sendBroadCast(JPushNotification notification) {
		String valid=validJpushNotification(notification);
		if(valid.length()>0){
			logger.error("推送校验参数失败,msg is "+valid);
			return;
		}
		SpringContextUtil.getApplicationContext().publishEvent(new JpushEvent(SpringContextUtil.getApplicationContext(),notification));
	}
	
	private String validJpushNotification(JPushNotification notification) {
		StringBuffer sb=new StringBuffer();
		if(notification==null){
			sb.append("notification is null");
			return sb.toString();
		}
//		Integer appId=notification.getAppId();
//		if(appId==null||appId<=0){
//			sb.append("appId不合法!,appId is "+appId);
//			return sb.toString();
//		}
		if(StringUtils.isTrimedEmpty(notification.getAlert())){
			sb.append("alert不合法,alert is "+notification.getAlert());
			return sb.toString();
		}

		if(StringUtils.isTrimedEmpty(notification.getTitle())){
			sb.append("title不合法,title is "+notification.getTitle());
			return sb.toString();
		}
		if(notification.getPlatform()==null||notification.getPlatform()<1||notification.getPlatform()>4){
			sb.append("platform不合法,platform is "+notification.getPlatform());
			return sb.toString();
		}
		return sb.toString();
	}


	@Override
	public void sendMessage(JPushMessage message) {
		SpringContextUtil.getApplicationContext().publishEvent(new JpushMessageEvent(SpringContextUtil.getApplicationContext(),message));
	}


	@Override
	public void sendNotification(JPushNotification notification) {
		logger.info("发送通知开始，入参是{}",JSON.toJSONString(notification));
		String valid=validJpushNotification(notification);
		if(valid.length()>0){
			logger.info("校验参数失败，入参是{}",JSON.toJSONString(notification));
			logger.error("推送校验参数失败,msg is "+valid);
			return;
		}
		logger.info("校验参数结束，入参是{}",JSON.toJSONString(notification));
		SpringContextUtil.getApplicationContext().publishEvent(new JpushNotificationEvent(SpringContextUtil.getApplicationContext(),notification));
	}
	
}
